<template>
  <div class="reg">
    <snackbars :value='showBar' :text='text'/>
    <v-form v-model="valid" ref="regForm">
      <v-text-field label="注册邮箱" :rules="rulesEmail" v-model="email" />
      <v-text-field
        label="密码"
        type="password"
        :rules="rulesPwd"
        v-model="pwd"
      />
      <v-text-field label="昵称" :rules="rulesNickName" v-model="nickName" />
    </v-form>
    <div class="btnGroup">
      <v-btn
        class="reg"
        style="
          background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);
          color: #fff;
        "
        @click="handleReg"
      >
        注册
      </v-btn>

      <v-btn
        class="reset"
        style="background-image: linear-gradient(to right, #f83600 0%, #f9d423 100%);color: #fff;
        "
        @click="handleReset"
      >
        重置
      </v-btn>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import {userReg,userRegAns} from '@/api/user'
import Snackbars from '@/components/Snackbars'
export default Vue.extend({
  name: "SignUp",
  data: () => ({
    showBar: false,
    text: '',
    email: "",
    pwd: "",
    nickName: "",
    valid: false,
    rulesEmail: [
      (value: string) => !!value || "邮箱不能为空",
      (value: string) =>
        (value &&
          /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) ||
        "邮箱格式不正确",
    ],
    rulesNickName: [
      (value: string) => !!value || "昵称不能为空",
      (value: string) => (value && value.length >= 2) || "最少2个字符",
    ],
    rulesPwd: [
      (value: string) => !!value || "密码不能为空",
      (value: string) =>
        (value &&
          /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/.test(value)) ||
        "密码必须在6-18为，并且包含字母与数字",
    ],
  }),
  methods: {
    handleReg() {
      const { regForm } = this.$refs as any;
      regForm.validate();
      if (this.valid) {
        const userId = this.email
        userReg(userId,this.nickName,this.email,this.pwd)
            .then(res => {
              const {msg} = res as unknown as userRegAns
              this.text = msg
              this.showBar = true
              setTimeout(() => {
                this.showBar = false
              },2000)
              regForm.reset();
            })
      }
    },
    handleReset() {
      const { regForm } = this.$refs as any;
      regForm.reset();
    },
  },
  components: {
    Snackbars
  }
});
</script>

<style lang="scss">
.reg {
  .btnGroup {
    margin-top: 2vh;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
  }
}
</style>